using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

namespace dkdm.danmuhelper.editorscript
{
    [InitializeOnLoad]
    public class CustomHierarchy
    {
        static CustomHierarchy()
        {
            EditorApplication.hierarchyWindowItemOnGUI += HandleHierarchyWindowItemOnGUI;
        }

        private static void HandleHierarchyWindowItemOnGUI(int instanceID, Rect selectionRect)
        {
            var obj = EditorUtility.InstanceIDToObject(instanceID);
            var go = obj as GameObject;
            // if (go != null)
            // {
            //     var rect = new Rect(selectionRect);
            //     rect.x = rect.width - 20;
            //     rect.width = 20;
            //     if (GUI.Button(rect, "C"))
            //     {
            //         Debug.Log("Clicked");
            //     }
            // }
            if (go == null)
            {
                return;
            }
            ShowComment(go, selectionRect);
        }

        private static void ShowComment(GameObject go, Rect selectionRect)
        {
            var comment = go.GetComponent<IHierarchyComment>();
            if (comment == null)
            {
                return;
            }
            var text = comment.HierachyComment;
            if (string.IsNullOrEmpty(text))
            {
                return;
            }
            {
                // background
                if (
                    go.TryGetComponent<IHierarchyBackgroundTexture>(out var bgTexture)
                    && bgTexture.Texture != null
                )
                {
                    EditorGUI.DrawPreviewTexture(
                        selectionRect,
                        bgTexture.Texture,
                        bgTexture.Material,
                        bgTexture.ScaleMode,
                        bgTexture.ImageAspect
                    );
                }
                else if (go.TryGetComponent<IHierarchyBackgroundColor>(out var bgColor))
                {
                    EditorGUI.DrawRect(selectionRect, bgColor.Color);
                }
            }
            // show in end of name
            // var rect = new Rect(selectionRect);
            // rect.x = rect.width - 20;
            // rect.width = 20;

            if (_commentStyle == null)
            {
                _commentStyle = new GUIStyle(EditorStyles.miniLabel);
                // _commentStyle.normal.textColor = Color.blue;
                _commentStyle.alignment = TextAnchor.MiddleRight;
            }

            EditorGUI.LabelField(selectionRect, text, _commentStyle);
        }

        private static GUIStyle _commentStyle;
    }
}
